﻿namespace UnityEngine.Rendering.Universal
{
    public class GlitchImageBlock : VolumeComponent, IPostProcessComponent
    {
        public BoolParameter ActiveOn = new BoolParameter(false, true);
        public ClampedFloatParameter fade = new ClampedFloatParameter(1.0f, 0.0f, 1.0f);
        public ClampedFloatParameter speed = new ClampedFloatParameter(0.5f, 0.0f, 1.0f);
        public ClampedFloatParameter amount = new ClampedFloatParameter(1.0f, 0.0f, 10.0f);
        public ClampedFloatParameter blockLayer1U = new ClampedFloatParameter(9.0f, 0.0f, 50.0f);
        public ClampedFloatParameter blockLayer1V = new ClampedFloatParameter(9.0f, 0.0f, 50.0f);
        public ClampedFloatParameter blockLayer1Indensity = new ClampedFloatParameter(8.0f, 0.0f, 50.0f);
        public ClampedFloatParameter blockLayer2U = new ClampedFloatParameter(5.0f, 0.0f, 50.0f);
        public ClampedFloatParameter blockLayer2V = new ClampedFloatParameter(5.0f, 0.0f, 5.0f);
        public ClampedFloatParameter blockLayer2Indensity = new ClampedFloatParameter(4.0f, 0.0f, 50.0f);
        public ClampedFloatParameter RBGSplitIndensity = new ClampedFloatParameter(0.5f, 0.0f, 50.0f);
        
        static readonly int m_ParamsId = Shader.PropertyToID("_Params");
        static readonly int m_ParamsId2 = Shader.PropertyToID("_Params2");
        static readonly int m_ParamsId3 = Shader.PropertyToID("_Params3");
        
        private float _timeX = 1.0f;
        
        public bool IsActive()
        {
            return active && ActiveOn.value;
        }

        public bool IsTileCompatible()
        {
            return false;
        }
        
        public override void SetActive(bool value)
        {
            base.SetActive(value);
            ActiveOn.overrideState = true;
            ActiveOn.value = value;
        }

        public override void UpdateVector3(float f1, float f2, float f3, int type = 0)
        {
            fade.overrideState = true;
            fade.value = f1;

            speed.overrideState = true;
            speed.value = f2;

            amount.overrideState = true;
            amount.value = f3;
        }

        public void Render(CommandBuffer cmd, Material material, RTHandle source, RTHandle destination)
        {
            _timeX += Time.deltaTime;
            if (_timeX > 100)
                _timeX = 0.0f;
            
            material.SetVector(m_ParamsId, new Vector3(_timeX * speed.value, amount.value, fade.value));
            material.SetVector(m_ParamsId2, new Vector4(blockLayer1U.value, blockLayer1V.value, blockLayer2U.value, blockLayer2V.value));
            material.SetVector(m_ParamsId3, new Vector3(RBGSplitIndensity.value, blockLayer1Indensity.value, blockLayer2Indensity.value));
            cmd.Blit(source, BlitDstDiscardContend(cmd, destination), material);
        }
    }
}